<template>
    <div class="map" v-if="prosps.hidden">
        <header class="marginBottom2">
            <button class="FontSize_word" @click="Back">&lt;&nbsp;&nbsp;返 回</button>
            <button class="FontSize_word" @click="test">生成物资</button>
            <button class="FontSize_word" @click="SeeItem('工具', '当前没有任何工具')">查看工具</button>
            <button class="FontSize_word" @click="SeeItem('消耗', '当前没有任何材料')">查看材料</button>
        </header>
        <main class="main FontSize_text">
            <div class="MainHead">
                <div><span>生成的物资将消耗10点饱和度，通过打开生成的宝箱可以获取各种消耗类物品。</span></div>
                <div><span>最多只能生成6个宝箱</span></div>
                <div class="box">
                    <div class="children" v-for="item in Main.Character.chest">
                        <span>
                            {{ item.evaluate == 1 ? "初级宝箱" : item.evaluate == 2 ? "中级宝箱" : item.evaluate == 3 ? "高级宝箱" :
                                "数据错误"
                            }}
                        </span>
                        <button style="margin:0;" class="FontSize_text" v-if="item.evaluate >= 1 && item.evaluate <= 3"
                            @click="SuppliesChest(item)">打开物资</button>
                    </div>
                    <div v-if="Main.Character.chest.length <= 0">
                        没有物资宝箱
                    </div>
                </div>
            </div>
            <div class="MainContnet">
                <div class="MainContnetBox" ref="MainContnetBox">
                    <div class="test1">
                        <div class="test" v-for="item in   Main.Character.survives  " :key="item.itemId">
                            <p>名称：{{ item.surviveName }}</p>
                            <p>等级：{{ item.lv }}</p>
                            <p v-if="item.status == 1 || item.status == 4">升级耗材：{{ item.upgrades }}</p>
                            <p>说明：{{ item.details }}</p>
                            <!-- 资源 -->
                            <p v-if="item.status == 2">
                                剩余资源： {{ item.durability }}/{{ item.totalDurability }}</p>
                            <!-- 操作 -->
                            <p>
                                <button class="FontSize_text" v-if="item.status == 1 || item.status == 4"
                                    @click="HomeAugment(item)">扩建</button>
                                <button class="FontSize_text" v-if="item.surviveType == 3" @click="build">建造</button>
                                <button class="FontSize_text" v-if="item.status == 2" @click="homeGather(item)">采集</button>
                                <button class="FontSize_text"
                                    v-if="item.status == 4 || item.surviveType == 19 || item.surviveType == 20"
                                    @click="DestroyBuilding(item)">摧毁</button>
                            <div v-if="item.surviveType == 1">
                                <button class="FontSize_text" @click="HomeConstruct(item, 17)">植树</button>
                                <button class="FontSize_text" @click="HomeConstruct(item, 18)">培植浆果</button>
                            </div>

                            <div v-if="item.surviveType == 15">
                                <button class="FontSize_text" @click="HomeConstruct(item, 21)">建矿</button>
                            </div>
                            <div v-if="item.surviveType == 11">
                                <button class="FontSize_text" @click="HomeConstruct(item, 17)">建园</button>
                            </div>
                            <div v-if="item.surviveType == 12">
                                <button class="FontSize_text" @click="HomeConstruct(item, 22)">养鱼</button>
                            </div>
                            <div v-if="item.surviveType == 16">
                                <button class="FontSize_text" @click="HomeConstruct(item, 24)">建矿</button>
                            </div>
                            <div v-if="item.surviveType == 13">
                                <button class="FontSize_text" @click="HomeConstruct(item, 23)">建矿</button>
                            </div>
                            <div v-if="item.surviveType == 14">
                                <button class="FontSize_text" @click="HomeConstruct(item, 18)">建园</button>
                            </div>
                            <button v-if="item.status == 4" class="FontSize_text" @click="Acquire(item)">获取</button>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </main>
        <!-- 查看工具弹窗 -->
        <Zky_BackpackPopup v-model:hidden="ToolPopup" :titleHidden="false" :FoorthHidden="false">
            <div class="ToolPopup">
                <div class="ToolPopupBox">
                    <div class="GirdProperty_XXXL GirdProperty_XXL GirdProperty_XL GirdProperty_X">
                        <div v-for="  item   in   ToolList  " :class="item.itemEvaluate == 2 ? 'Color2' : 'Color3'"
                            class="ToolPopupUse">
                            <p>{{ item.itemName }}*{{ item.itemNum }}</p>
                            <p v-if="item.itemType == '工具'">耐久度：{{ item.itemGrow }}</p>
                        </div>
                    </div>
                </div>
            </div>
        </Zky_BackpackPopup>
        <!-- 摧毁建筑弹窗 -->
        <Zky_Popup v-model:hidden="DestroyPopup" :title="'摧毁建筑'" :Confirm="DestroyComfirm">
            <span class="FontSize_text">摧毁土地需要消耗一份炸药，便可以将该土地变成初始状态</span>
        </Zky_Popup>
        <!-- 建造工具弹窗 -->
        <Zky_Popup v-model:hidden="toolPopup" :title="'建造工具'" :ConfirmlHidden="false">
            <div style="text-align: center;" class="marginBottom1">
                <select style="width: 80%;height:30px;" v-model="Option" calss="FontSize_text" @change="ToolChange">
                    <option value="">请选择打造工具</option>
                    <option v-for="item in toolOption" :value="item.value">{{ item.name }}</option>
                </select>

            </div>
            <div v-if="ToolConsumable" style="text-align: center;" class="marginBottom1">
                消耗材料： {{ ToolConsumable }}
            </div>
            <div style="text-align: center;">
                <button class="FontSize_word" @click="buildItem">打造</button>
            </div>

        </Zky_Popup>
        <!-- 兑换码/获得物品奖励弹窗 -->
        <Zky_BackpackPopup v-model:hidden="RewardsPopup">
            <div class="CDKEYRewardsStyle GirdCropland_XXXL GirdCropland_XXL GirdCropland_XL GirdCropland_X"
                style="text-align: center;">
                <div v-for="  item   in   RewardsItem  ">
                    <span
                        :class="item.itemEvaluate == 1 ? '' : item.itemEvaluate == 2 ? 'Color2' : item.itemEvaluate == 3 ? 'Color3' : ''">{{
                            item.itemName }}</span>*<span>{{ item.itemNum }}</span>
                </div>
            </div>
        </Zky_BackpackPopup>
        <!-- 初始化数据 -->
        <!-- <Zky_Loading v-model:hidden="Loging">
        </Zky_Loading> -->
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick } from "vue"
import Axios from "../../Axios";
import { main } from "../../store";
import Alert from "../../components/Com/Alert/index"

const Main = main()
const prosps = defineProps(["hidden"])
const emit = defineEmits(["update:hidden"])
const Loging = ref(false)
const max = ref("0px") // 控制当前物资宽度
const ToolList = ref()  // 当前物资数组
const ToolPopup = ref(false) // 控制物资弹窗显示
const branch = ref(0) // 控制当前地图每一行显示内容
const MainContnetBox = ref(0) // 温馨的家dom元素
const ChestFlag = ref(true)  // 控制宝箱节流
const RewardsItem = ref([]) // 奖励物品数组
const RewardsPopup = ref(false) // 奖励弹窗显示
const toolPopup = ref(false) //  控制工具弹窗显示
const Option = ref("")  // 当前被选中的工具
const OptionName = ref("") // 获取当前选中的工具名称
const ToolConsumable = ref("")// 当前打造工具需要消耗的材料
const DestroyPopup = ref(false) // 控制摧毁弹窗显示
const DestroyList = ref("") // 需要摧毁的地块格信息
// 打造所有工具需要消耗的材料
const ListTool = ref([
    {
        value: "gong1",
        list: [{
            name: "木材",
            num: 10
        }]
    },
    {
        value: "gong2",
        list: [{
            name: "石料",
            num: 8
        }, {
            name: "铁料",
            num: 6
        }]
    },
    {
        value: "gong3",
        list: [{
            name: "木材",
            num: 10
        }]
    },
    {
        value: "gong4",
        list: [{
            name: "石料",
            num: 8
        }, {
            name: "铁料",
            num: 5
        }]
    }
])
// 初始化建造数据
const toolOption = ref([{
    value: "gong1",
    name: "万能镐"
}, {
    value: "gong2",
    name: "炸药"
}, {
    value: "gong3",
    name: "万能斧"
}, {
    value: "gong4",
    name: "渔网"
}])
// 返回
const Back = () => {
    emit("update:hidden", false)
}
// 建造物品
const buildItem = async () => {
    if (!OptionName.value) {
        Alert({
            title: "还没有需要打造的物品",   // 渲染的内容，
            type: "error",
            time: 2000
        })
        return
    }
    let survive = Main.Character.survives.filter(el => el.surviveType === 2)[0]
    switch (OptionName.value) {
        case "gong1":
            if (survive.lv < 3) {
                Alert({
                    title: "工作台等级小于3级无法打造",   // 渲染的内容，
                    type: "error",
                    time: 2000
                })
                return
            }
            break
        case "gong2":
            if (survive.lv < 8) {
                Alert({
                    title: "工作台等级小于8级无法打造",   // 渲染的内容，
                    type: "error",
                    time: 2000
                })
                return
            }
            break
        case "gong4":
            if (survive.lv < 5) {
                Alert({
                    title: "工作台等级小于8级无法打造",   // 渲染的内容，
                    type: "error",
                    time: 2000
                })
                return
            }
            break
    }

    const res = await Axios("/Game/ForgeTool", "POST", { itemId: OptionName.value });
    if (res.code == 200) {

        Main.ADDCHARACTERS()
        Alert({
            title: res.message,   // 渲染的内容，
            time: 2000
        })

    } else {
        Alert({
            title: res.message,   // 渲染的内容，
            type: "error",  //组件类型
            time: 2000
        })
    }

}
// 切换需要打造的工具
const ToolChange = (e) => {
    OptionName.value = e.target.value;
    if (OptionName.value) {
        let list = ListTool.value.filter(el => el.value == OptionName.value)[0]
        // 获取求生大师数据
        let profession = Main.Character.profession.filter(el => el.professionId == "2")[0]

        if (profession.professionStatus == 1) {
            let index = 0
            switch (profession.professionBranch[0].occupationId) {
                case "1":
                    index = 0
                    break;
                case "2":
                    index = 0.2
                    break;
                case "3":
                    index = 0.4
                    break;
                default:
                    break;
            }
            list.list.forEach(el => {
                el.num = el.num - Math.floor(el.num * index)
            })
        }
        ToolConsumable.value = ""
        list.list.forEach((el, index) => {
            ToolConsumable.value += list.list.length - 1 == index ? `${el.name}*${el.num}` : `${el.name}*${el.num}、`
        })
    } else {
        ToolConsumable.value = ""
    }

}
// 建造按钮
const build = () => {
    toolPopup.value = true
}
// 打开物资宝箱
const SuppliesChest = async (item) => {
    const res = await Axios("/Game/OpenChest", "POST", item);
    if (res.code == 200) {

        Main.ADDCHARACTERS()
        RewardsItem.value = []
        RewardsItem.value = res.data
        RewardsPopup.value = true

    } else {
        Alert({
            title: res.message,   // 渲染的内容，
            type: "error"  //组件类型
        })
    }

}

// 获取自定义物资
const Acquire = async (item) => {
    if (new Date(item.time).getTime() + 1000 * 60 * 5 > new Date().getTime()) {
        Alert({
            title: "物资正在生长，请稍等",   // 渲染的内容，
            type: "error",
            time: 2000
        })
        return
    }
    const res = await Axios("/Game/Acquire", "POST", item);
    if (res.code == 200) {
        Main.ADDCHARACTERS()
        RewardsItem.value = []
        RewardsItem.value = res.data
        RewardsPopup.value = true
    } else {
        Alert({
            title: res.message,   // 渲染的内容，
            type: "error"  //组件类型
        })
    }
}
// 扩建建筑
const HomeAugment = async (item) => {
    const res = await Axios("/Game/Augment", "POST", item);
    if (res.code == 200) {
        Alert({
            title: "建造完成",   // 渲染的内容，
        })
        await Main.ADDCHARACTERS()
        branch.value = Math.sqrt(Main.Character.survives.length)
        if (item.surviveType == 2) {
            let num = branch.value - 1
            let num1 = 0
            for (let index = 1; index <= branch.value; index++) {
                if (2 * index - num == 0) {
                    num1 = index
                }
            }
            if (num1 == 0) {
                throw ("非法数据")
            }
            let test = document.querySelectorAll(".test")
            let num3 = (num - 1) * 20 - 20
            nextTick(() => {
                MainContnetBox.value.scrollTop = 280 * num1 + num3
                MainContnetBox.value.scrollLeft = test[0].clientWidth * (num1 - 1) + num3
            })
        }

    } else {
        Alert({
            title: res.message,   // 渲染的内容，
            type: "error"  //组件类型
        })
    }

}
// 
const DestroyComfirm = async () => {
    const res = await Axios("/Game/DestroyBuilding", "POST", DestroyList.value);
    if (res.code == 200) {
        Alert({
            title: "建造完成",   // 渲染的内容，
        })
        DestroyPopup.value = false
        Main.ADDCHARACTERS()
    } else {
        Alert({
            title: res.message,   // 渲染的内容，
            type: "error"  //组件类型
        })
    }
}
// 摧毁建筑按钮
const DestroyBuilding = async (item) => {
    DestroyList.value = ""
    DestroyList.value = item
    DestroyPopup.value = true
}
// 建造
const HomeConstruct = async (item, num) => {
    let items = JSON.parse(JSON.stringify(item))
    items.surviveType = num

    const res = await Axios("/Game/Construct", "POST", items);
    if (res.code == 200) {
        Alert({
            title: "建造完成",   // 渲染的内容，
        })
        Main.ADDCHARACTERS()
    } else {
        Alert({
            title: res.message,   // 渲染的内容，
            type: "error"  //组件类型
        })
    }
}
// 查询物品
const SeeItem = (type, title) => {

    let item = Main.Character.itemDetails.filter(el => el.itemType == type)
    if (item.length < 0) {
        Alert({
            title: title,
            type: "error",
            time: 2000
        })
        return
    }
    ToolPopup.value = true
    ToolList.value = JSON.parse(JSON.stringify(item))
}
// 采集物资
const homeGather = async (item) => {
    if (item.surviveType == 9 || item.surviveType == 6 || item.surviveType == 8) {
        let arr = Main.Character.itemDetails.filter(el => el.itemId == "gong1")
        if (arr.length <= 0) {
            Alert({
                title: "没有对应工具无法开采",
                type: "error",
                time: 2000
            })
            return
        }
    } else if (item.surviveType == 4) {
        let arr = Main.Character.itemDetails.filter(el => el.itemId == "gong3")
        if (arr.length <= 0) {
            Alert({
                title: "没有对应工具无法开采",
                type: "error",
                time: 2000
            })
            return
        }
    } else if (item.surviveType == 5) {
        let arr = Main.Character.itemDetails.filter(el => el.itemId == "gong4")
        if (arr.length <= 0) {
            Alert({
                title: "没有对应工具无法捕捉",
                type: "error",
                time: 2000
            })
            return
        }
    }
    const res = await Axios("/Game/Gather", "POST", item);
    if (res.code == 200) {
        Alert({
            title: `${res.data.itemName}加${res.data.itemNum}`,   // 渲染的内容，
        })
        Main.ADDCHARACTERS()
    } else {
        Alert({
            title: res.message,   // 渲染的内容，
            type: "error"  //组件类型
        })
    }
}

const test = async () => {
    if (Main.Character.chest >= 6) {
        Alert({
            title: "最多同时存在六个物资",
            type: "error",
            time: 2000
        })
        return
    }
    if (ChestFlag.value) {
        ChestFlag.value = false
        const res = await Axios("/Game/GenerateChest", "POST");
        if (res.code == 200) {
            Alert({
                title: "获取物资成功",   // 渲染的内容，
            })
            await Main.ADDCHARACTERS()
            supplies()
        } else {
            Alert({
                title: res.message,   // 渲染的内容，
                type: "error"  //组件类型
            })
        }
        ChestFlag.value = true
    } else {
        if (Main.Character.chest >= 6) {
            Alert({
                title: "请等待宝箱生成",
                type: "error",
                time: 2000
            })

        }
    }

}
// 用于计算当前的物资
const supplies = async () => {
    let box = document.querySelector(".box")
    let children = document.querySelectorAll(".children")
    max.value = `${Math.floor(box.clientWidth / 6)}px`
    if (children.length > 0) {
        for (let index = 0; index < children.length; index++) {
            await setTimeout(() => {
                children[index].style.left = `${Math.floor(index * (box.clientWidth / 6))}px`
            }, 100)

        }
    }

}
window.addEventListener("resize", () => {
    supplies()
    if (ch.length > 0) {
        ch.forEach((el, index) => {
            el.style.left = `${box.clientWidth / 6 * index}px`
        })
    }

})


onMounted(async () => {
    supplies()
    branch.value = Math.sqrt(Main.Character.survives.length)


    let num = branch.value - 1
    let num1 = 0
    for (let index = 1; index <= branch.value; index++) {
        if (2 * index - num == 0) {
            num1 = index
        }
    }
    if (num1 == 0) {
        throw ("非法数据")
    }
    let test = document.querySelectorAll(".test")
    let num3 = (num - 1) * 20
    nextTick(() => {
        MainContnetBox.value.scrollTop = 280 * num1 + num3
        MainContnetBox.value.scrollLeft = test[0].clientWidth * (num1 - 1) + num3
    })


})
onBeforeUnmount(() => {
})
</script>

<style lang="scss" scoped>
.ToolPopup {
    height: 60vh;

    .ToolPopupBox {
        height: 100%;
        overflow-y: auto;

        .ToolPopupUse {
            border: 1px solid #888;
            text-align: center;
        }
    }
}

.main {
    height: 90%;
    width: 100%;

    .MainHead {
        height: 30%;
        width: 100%;
    }

    .MainContnet {
        height: 70%;
        width: 100%;
        border: 1px dashed #888;

        .MainContnetBox {
            width: 100%;
            height: 100%;
            overflow: auto;

            .test1 {

                display: grid;
                grid-template-columns: repeat(v-bind(branch), 40%);
                padding: 20px;
                justify-items: center;
                align-items: center;
                box-sizing: border-box;
                gap: 20px;
            }

            .test {
                width: 100%;
                height: 280px;
                box-sizing: border-box;
            }
        }
    }

    .box {
        background: red;
        width: 100%;
        height: 50%;
        position: relative;


        .children {
            position: absolute;
            top: 0;
            width: v-bind(max);
            height: 100%;
            left: 100%;
            transition: all 2s;
            border: 1px dashed #888;
            padding: 6px;
            box-sizing: border-box;
            text-align: center;
            display: grid;
            align-items: center;
        }
    }
}

.map {
    height: 100%;


}

.MapDetailsPopup {
    text-indent: 2em;
}

.Color2 {
    color: #00FFFF !important;
}

.Color3 {
    color: #FAC000 !important;
}
</style>